package sunyu.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sunyu.mapper.ShiroRoleMapper;
import sunyu.mapper.ShiroRoleResourceMapper;
import sunyu.pojo.ShiroRole;
import sunyu.pojo.ShiroRoleResourceKey;
import sunyu.service.RoleService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 孙宇
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    ShiroRoleMapper shiroRoleMapper;

    @Resource
    ShiroRoleResourceMapper shiroRoleResourceMapper;

    @Override
    public List<ShiroRole> select(Map params) {
        return shiroRoleMapper.select(params);
    }

    @Override
    @Transactional
    public void insertRoleAndResource(ShiroRole record, List<String> resourceIds) {
        shiroRoleMapper.insert(record);
        if (resourceIds != null && resourceIds.size() > 0) {
            for (String id : resourceIds) {
                ShiroRoleResourceKey rr = new ShiroRoleResourceKey();
                rr.setRole_id(record.getId());
                rr.setResource_id(id);
                shiroRoleResourceMapper.insert(rr);
            }
        }
    }

    @Override
    @Transactional
    public void updateRoleAndResource(ShiroRole record, List<String> resourceIds) {
        shiroRoleMapper.updateByPrimaryKey(record);

        Map params = new HashMap();
        params.put("role_id", record.getId());
        shiroRoleResourceMapper.delete(params);

        if (resourceIds != null && resourceIds.size() > 0) {
            for (String id : resourceIds) {
                ShiroRoleResourceKey rr = new ShiroRoleResourceKey();
                rr.setRole_id(record.getId());
                rr.setResource_id(id);
                shiroRoleResourceMapper.insert(rr);
            }
        }
    }

    @Override
    public List<String> selectResourceIds(String roleId) {
        Map params = new HashMap();
        params.put("role_id", roleId);
        return shiroRoleResourceMapper.selectResourceIds(params);
    }

    @Override
    public int deleteByPrimaryKey(String id) {
        return shiroRoleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(ShiroRole record) {
        return shiroRoleMapper.insert(record);
    }

    @Override
    public int insertSelective(ShiroRole record) {
        return shiroRoleMapper.insertSelective(record);
    }

    @Override
    public ShiroRole selectByPrimaryKey(String id) {
        return shiroRoleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(ShiroRole record) {
        return shiroRoleMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(ShiroRole record) {
        return shiroRoleMapper.updateByPrimaryKey(record);
    }
}
